// pages/album/album.js
const app = getApp()
const qiniu = require("../../utils/qiniu.min.js");
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    actId:'',
    status:0,
    checked:false,
    isOpen:false,
    imageUrl:[],
    tempFilePathArray:[],
    picArr:[{
      selected: false,
      image:'https://centlingimg.yunjudata.com/23e591cb-a1e8-4197-b6e2-38ba05d39050.jpg',
    }
    ],
    images:[],
    originatorID:'',
    user:{},
    userID:''
  },

// 相册管理
  management:function() {
    //0 是活动结束前，1是活动结束后    为了埋点区分开
    if (this.data.status == 1) {
      app.TestBuriedPoint('yqlw_end_see_administration')
    } else {
      app.TestBuriedPoint('yqlw_enroll_album_administration')
    }
    var that = this;
    if(that.data.imageUrl.length > 0) {
      that.setData({
        isOpen: true
      })
    } else {
      wx.showToast({
        title: "相册为空",
        icon: 'none',
        duration: 2000
      })
    }

  },
  management1: function () {
    //0 是活动结束前，1是活动结束后    为了埋点区分开
    
    var that = this;
      that.setData({
        isOpen: false
      })
  },

  //图片上传
  changeBg: function () {
    //0 是活动结束前，1是活动结束后    为了埋点区分开
    if(this.data.status == 1){
      app.TestBuriedPoint('yqlw_end_see_upload')
    }else{
      app.TestBuriedPoint('yqlw_enroll_album_upload')
    }
    var that = this;
    that.setData({
      isOpen:false
    })
    console.log("传.............")
    app.getQiNiuToken(function (res) {
      var qiniuconfig = res;
      console.log("进入qn", qiniuconfig)
      wx.chooseImage({
        count:9,
        siradioeType: ['original', 'compressed'],
        sourceType: ['camera','album'],
        success: function (res) {
          const filepathArray = res.tempFilePaths
          // console.log('图片地址', filepathArray)
          for (let i = 0; i < filepathArray.length; i++) {
            // console.log('进入循环', filepathArray)
            wx.showLoading({
              title: '图片上传中',
            })
            qiniu.upload(filepathArray[i], res => {
              console.log("图片列表", [res.imageURL])
              that.setData({
                tempFilePathArray: that.data.tempFilePathArray.concat([res.imageURL])
              })
              wx.hideLoading()
              if (that.data.tempFilePathArray.length == filepathArray.length) {
                console.log("七牛返回的图片地址", that.data.tempFilePathArray)
                console.log("我走了i:",i)
                that.uploadImage(that.data.tempFilePathArray)
              }
            }, (error) => {
              wx.hideLoading()
              wx.showToast({
                title: '请求超时，请稍后重试',
                icon: 'none',
                duration: 2000
              })
              console.log('error' + error)
            }, {
                uploadURL: 'https://upload.qiniup.com',
                region: 'ECN',
                domain: qiniuconfig.qiniuDomain,
                uptoken: qiniuconfig.upToken,
              })
          }
        }
      })
    });
  },
  //选择
  radioList:function(e) {
    var that = this;
    var userId = this.data.user.id;
    // 获取选中的radio索引
    var index = e.currentTarget.dataset.index;
    // 获取到商品列表数据
    var list = that.data.imageUrl;
    // 循环数组数据，判断----选中/未选中[selected]
    console.log('选择', index)
    if (list[index].createUid == userId || that.data.originatorID == userId) {
      list[index].flag = !list[index].flag;
    }
    // 如果数组数据全部为selected[true],全选
    for (var i = list.length - 1; i >= 0; i--) {
      if (!list[i].flag) {
        that.setData({
          checked: false
        })
      }else{
        that.setData({
          checked: true
        })
      }
    }
    // 重新渲染数据
    that.setData({
      imageUrl: list,
      checked: that.data.checked
    })

  },
  //全选
  radio(e) {
    // 全选ICON默认选中
    let checked = this.data.checked;
    // true  -----   false
    checked = !checked;
    // 获取商品数据
    let list = this.data.imageUrl;
    var userId = this.data.user.id;
    if (this.data.originatorID == userId) {
      // 循环遍历判断列表中的数据是否选中
      for (let i = 0; i < list.length; i++) {
        list[i].flag = checked;
      }
      // 页面重新渲染
      this.setData({
        checked: checked,
        imageUrl: list
      });
    } else {
      // 循环遍历判断列表中的数据是否选中
      for (let i = 0; i < list.length; i++) {
        console.log("checked", checked)
        if (list[i].createUid == userId) {
          list[i].flag = checked;
        }
      }
      // 页面重新渲染
      this.setData({
        checked: checked,
        imageUrl: list
      });
    }
    
  },
  //图片点击预览
  previewImg: function (e) {
    // console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index;
    var imgArr = [];
    console.log('图片地址', this.data.imageUrl)
    for (var i = 0; i < this.data.imageUrl.length;i++){
      imgArr.push(this.data.imageUrl[i].posterUrl);
    };
     console.log(imgArr);
    wx.previewImage({
      current: imgArr[index],     //当前图片地址
      urls: imgArr,               //所有要预览的图片的地址集合 数组形式
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  //删除
  removeImage(e) {
    // const idx = e.target.dataset.idx
    // this.data.images.splice(idx, 1)
    // $digest(this)
    var that = this
    console.log(that.data.imageUrl)
    let list = that.data.imageUrl;
    var flagArray = []
    for (let i = 0; i < list.length; i++) {
      if (list[i].flag == true) {
        flagArray = flagArray.concat(list[i].id)
      }
    }
    console.log("flagArray", flagArray)
    if (flagArray.length > 0) {
      var gs = flagArray.length
      wx.showModal({
        content: '是否删除'+ gs + '张相片？',
        cancelText: "返回",
        confirmText: "删除",
        confirmColor: '#333333',
        cancelColor: '#3680FE',
        success(res) {
          if (res.confirm) {
            that.deleteImage(flagArray)
          }
        }
      })
    } else {
      wx.showToast({
        title: "请选择要删除的图片",
        icon: 'none',
        duration: 2000
      })
    }
  },

  //删除图片
  deleteImage(deleteImageArray){
    console.log("deleteImageArray", deleteImageArray)
    var that = this;
    wx.showLoading({ title: '请稍后', })
    app.req({
      url: "wechat/activity/deleteActPoster",
      method: "post",
      data: {
        id: deleteImageArray
      },
      success: function (res) {
        if (200 == res.code) {
          console.log("删除成功")
          // wx.hideLoading()
          wx.showToast({
            title: '已删除',
            duration: 2000
          })
          that.getImageList()
        } else {
          console.log("删除失败")
          wx.hideLoading()
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },


  //上传图片
  uploadImage(images) {
    console.log("images==",images)
    var that = this;
    wx.showLoading({ title: '上传中', })
    app.req({
      url: "wechat/activity/addPosterByAlbum",
      method: "post",
      data: {
        actId: that.data.actId,
        postersUrl: images
      },
      success: function (res) {
        if (200 == res.code) {
          wx.hideLoading()
          that.getImageList()
          that.setData({
            tempFilePathArray:[]
          })
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },


  //获取相册列表
  getImageList() {
    var that = this;
    // wx.showLoading({ title: '加载中', })
    app.req({
      url: "wechat/activity/album",
      method: "post",
      data: {
        actId: that.data.actId
      },
      success: function (res) {
        if (200 == res.code) {
          console.log("获取相册列表",res)
          that.setData({
            imageUrl:res.data
          })
          if (that.data.imageUrl.length < 1) {
            that.setData({
              isOpen:false
            })
          }

          wx.hideLoading()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      actId: options.id,
      status: options.status,
      originatorID: options.originatorID
    })
    app.getUserInfo(function (userInfo) {
      that.setData({
        user: userInfo,
        userID:userInfo.id
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getImageList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})